import 'dart:convert';
import 'package:fluro/fluro.dart';
import 'package:flutter/material.dart';
import 'package:flutter_dwh5/routes.dart';

// 全局key，用于无context跳转的情况
final GlobalKey<NavigatorState> navigatorKey = GlobalKey<NavigatorState>();

class NavigatorUtil {
  // 处理url参数拼接
  static String _getPathParams({Map<String, String> params, path}) {
    if (params != null) {
      // Utf8Encoder,解决参数有特殊字符，中文不能传递的情况
      String p = params.entries
          .map((e) =>
              '${e.key}=${jsonEncode(const Utf8Encoder().convert(e.value))}')
          .join('&');
      path = '$path?$p';
    }
    return path;
  }

  // 无context跳转
  static Future<dynamic> push(
    String path, {
    Map<String, String> params,
    bool replace = false,
    bool clearStack = false,
    Object arguments,
    TransitionType transition,
  }) {
    // 拼接params参数
    path = _getPathParams(params: params, path: path);
    // 这个结果是返回上一个页面携带的参数
    return Routes.router.navigateTo(
      navigatorKey.currentContext,
      path,
      replace: replace,
      clearStack: clearStack,
      transition: transition ?? TransitionType.inFromRight,
      // routeSettings需要在对应页面接收：ModalRoute.of(context)?.settings.arguments;
      routeSettings: RouteSettings(
        arguments: arguments,
      ),
    );
  }

  // 无context replase
  static Future<dynamic> replase(
    String path, {
    Map<String, String> params,
    bool replace = true,
    bool clearStack = false,
    Object arguments,
  }) {
    // 拼接params参数
    path = _getPathParams(params: params, path: path);
    return Routes.router.navigateTo(
      navigatorKey.currentContext,
      path,
      replace: replace,
      clearStack: clearStack,
      transition: TransitionType.inFromRight,
      // routeSettings需要在对应页面接收：ModalRoute.of(context)?.settings.arguments;
      routeSettings: RouteSettings(
        arguments: arguments,
      ),
    );
  }

  // 无context，清空路由栈跳转，一般用于跳转首页这种情况
  static Future<dynamic> switchTab(
    String path, {
    Map<String, String> params,
    bool replace = false,
    bool clearStack = true,
    Object arguments,
  }) {
    // 拼接params参数
    path = _getPathParams(params: params, path: path);
    return Routes.router.navigateTo(
      navigatorKey.currentContext,
      path,
      replace: replace,
      clearStack: clearStack,
      transition: TransitionType.inFromRight,
      // routeSettings需要在对应页面接收：ModalRoute.of(context)?.settings.arguments;
      routeSettings: RouteSettings(
        arguments: arguments,
      ),
    );
  }

  // 无context返回,并指定路由返回多少层，默认返回上一页面, 返回带参数params
  static void back({int count = 1, Object arguments}) {
    NavigatorState state = Navigator.of(navigatorKey.currentContext);
    while (count-- > 0) {
      state = state..pop(arguments);
    }
  }
}
